import { Ref, SetupContext, computed } from "vue";
import { UseFormat, UseNumber, UseSpinner, UseTextBox } from "./types";
import { NumberRangeProps } from "../number-range.props";

export function useTextBox(
    props: NumberRangeProps,
    context: SetupContext,
    displayValue: Ref<string>,
    modelValue: Ref<string | number>, useFormatComposition: UseFormat,
    useNumberComposition: UseNumber,
    useSpinnerComposition: UseSpinner,
    valueChangedCallback: (numberValue: number | string) => void
): UseTextBox {
    const { cleanFormat, format } = useFormatComposition;
    const { getRealValue, isEmpty } = useNumberComposition;
    const { downward, upward } = useSpinnerComposition;
    const textBoxValue = computed(() => displayValue.value);
    /**
     * 输入框失焦时执行的方法
     */
    function onBlurTextBox($event: Event) {
        $event.stopPropagation();
        if (props.readonly || props.disabled) {
            return;
        }
        const textValue = cleanFormat(($event.target as HTMLTextAreaElement)?.value || 0);
        displayValue.value = format(textValue);
        modelValue.value = getRealValue(textValue);
        valueChangedCallback(modelValue.value);
        context.emit('blur', { event: $event, formatted: displayValue.value, value: modelValue.value });
    }

    /**
     * 输入框获取焦点时执行的方法
     */
    function onFocusTextBox($event: Event) {
        $event.stopPropagation();
        if (props.readonly || props.disabled) {
            return;
        }
        displayValue.value = isEmpty(modelValue.value) ? '' : !props.showZero && modelValue.value === '0' ? '' : String(modelValue.value);
        context.emit('focus', { event: $event, formatted: displayValue.value, value: modelValue.value });
    }

    /**
     * 输入框的input事件
     */
    function onInput($event: Event) {
        $event.stopPropagation();
        const textValue = cleanFormat(($event.target as HTMLTextAreaElement)?.value || 0);
        displayValue.value = textValue;
        modelValue.value = getRealValue(textValue);
        valueChangedCallback(modelValue.value);
    }

    /**
     * 焦点状态下键盘监听事件
     */
    function onKeyDown($event: KeyboardEvent) {
        if ($event.key === 'ArrowDown') {
            $event.preventDefault();
            downward();
        }
        if ($event.key === 'ArrowUp') {
            $event.preventDefault();
            upward();
        }
        $event.stopPropagation();
    }

    return { textBoxValue, onBlurTextBox, onFocusTextBox, onInput, onKeyDown };
}
